#!/bin/bash

# Define
IMAGE="ccr.ccs.tencentyun.com/my.repo/newsletter-subs:v1.29"
CONTAINER_NAME="newsletter-subs"
HOST_CONFIG_DIR="/home/lighthouse/container/config"
HOST_OPT_DIR="/home/lighthouse/container/opt"
CONTAINER_CONFIG_DIR="/app/config"
CONTAINER_OPT_DIR="/app/opt"
HOST_PORT="8080"
CONTAINER_PORT="8080"
NETWORK_MODE="host"

# Check Docker
if ! command -v docker &> /dev/null; then
    echo "Docker could not be found. Please install Docker first."
    exit 1
fi

# Check foler in the host
if [ ! -d "$HOST_CONFIG_DIR" ]; then
    echo "Host directory $HOST_CONFIG_DIR does not exist."
    exit 1
fi

if [ ! -d "$HOST_OPT_DIR" ]; then
    echo "Host directory $HOST_OPT_DIR does not exist."
    exit 1
fi

# Check container if exist
if docker ps -a -f "name=$CONTAINER_NAME" --quiet; then
    echo "Container $CONTAINER_NAME is already running or exists. Stopping and removing it..."
    docker stop $CONTAINER_NAME
    docker rm $CONTAINER_NAME
fi

# Run container
docker run --net=$NETWORK_MODE \
    -v $HOST_CONFIG_DIR:$CONTAINER_CONFIG_DIR \
    -v $HOST_OPT_DIR:$CONTAINER_OPT_DIR \
    -d --name $CONTAINER_NAME \
    -p $HOST_PORT:$CONTAINER_PORT \
    $IMAGE

# Check result
if [ $? -eq 0 ]; then
    echo "Container $CONTAINER_NAME started successfully."
else
    echo "Failed to start container $CONTAINER_NAME."
    exit 1
fi
   